<template>
  <div class="plc-address-config">
    <app-header/>
    <main>
      <!-- 操作栏 -->
      <div class="actions-bar">
        <div class="filters">
          <div class="filter-group">
            <label for="station-filter" class="filter-label">工位</label>
            <select id="station-filter" v-model="filters.station" class="filter-select">
              <option value="all">全部工位</option>
              <option value="station1">工位1</option>
              <option value="station2">工位2</option>
            </select>
          </div>

          <div class="filter-group">
            <label for="category-filter" class="filter-label">类别</label>
            <select id="category-filter" v-model="filters.category" class="filter-select">
              <option value="all">全部类别</option>
              <option value="realtime">实时工艺</option>
            </select>
          </div>
        </div>

        <div class="actions">
          <button @click="navigateToAddAddress" class="hmi-button hmi-button-primary">
            <i class="fas fa-plus"></i> 添加地址
          </button>
        </div>
      </div>

      <!-- 表格内容 -->
      <div v-if="isLoading" class="loading-state">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>

      <div v-else-if="filteredAddresses.length === 0" class="empty-state">
        <div class="empty-icon">
          <i class="fas fa-list"></i>
        </div>
        <h3 class="empty-title">暂无地址数据</h3>
        <p class="empty-description">
          {{ hasAddresses ? '没有符合当前筛选条件的地址' : '点击"添加地址"按钮创建第一个PLC地址' }}
        </p>
        <button v-if="!hasAddresses" @click="navigateToAddAddress" class="hmi-button hmi-button-primary">
          <i class="fas fa-plus"></i> 添加地址
        </button>
        <button v-else @click="resetFilters" class="hmi-button hmi-button-secondary">
          <i class="fas fa-sync"></i> 重置筛选条件
        </button>
      </div>

      <div v-else class="table-container">
        <table class="address-table">
          <thead>
          <tr>
            <th>地址</th>
            <th>属性名称</th>
            <th>工位</th>
            <th>类别</th>
            <th>数据类型</th>
            <th>描述</th>
            <th class="actions-column">操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="address in filteredAddresses" :key="address.id" class="address-row">
            <td class="address-cell">{{ address.address }}</td>
            <td class="property-name-cell">{{ address.propertyName }}</td>
            <td>
                <span class="station-badge" :class="`station-${address.station}`">
                  {{ getStationName(address.station) }}
                </span>
            </td>
            <td>
                <span class="category-badge" :class="`category-${address.category}`">
                  {{ getCategoryName(address.category) }}
                </span>
            </td>
            <td>{{ address.type }}</td>
            <td class="description-cell">{{ address.description }}</td>
            <td class="actions-cell">
              <button @click="editAddress(address.id)" class="table-action-btn edit-btn" title="编辑">
                <i class="fas fa-edit"></i>
              </button>
              <button @click="goToDeleteConfirmPage(address)" class="table-action-btn delete-btn" title="删除">
                <i class="fas fa-trash-alt"></i>
              </button>
            </td>
          </tr>
          </tbody>
        </table>
      </div>
    </main>

    <!-- 通知消息 -->
    <div v-if="notification.show" class="notification"
         :class="{ 'notification-success': notification.type === 'success', 'notification-error': notification.type === 'error' }">
      <span>{{ notification.message }}</span>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive, computed, onMounted, onBeforeUnmount} from 'vue';
import {useRouter} from 'vue-router';
import AppHeader from '@/components/AppHeader.vue';
import plcAddressStore from '@/api/plcAddress';
import {logger} from '@/utils/logger';

const router = useRouter();

// --- 响应式数据 ---
// 地址列表
const addresses = ref([]);
const isLoading = ref(true);

// 筛选条件
const filters = reactive({
  station: 'all',
  category: 'all',
  search: ''
});

// 通知消息状态
const notification = reactive({
  show: false,
  message: '',
  type: 'success', // 'success' 或 'error'
  timeoutId: null
});

// --- 计算属性 ---
// 筛选后的地址列表
const filteredAddresses = computed(() => {
  let result = [...addresses.value];

  // 工位筛选
  if (filters.station !== 'all') {
    result = result.filter(addr => addr.station === filters.station);
  }

  // 类别筛选
  if (filters.category !== 'all') {
    result = result.filter(addr => addr.category === filters.category);
  }

  // 搜索筛选
  if (filters.search.trim()) {
    const searchTerm = filters.search.trim().toLowerCase();
    result = result.filter(addr =>
        addr.address.toLowerCase().includes(searchTerm) ||
        (addr.propertyName && addr.propertyName.toLowerCase().includes(searchTerm)) ||
        addr.description.toLowerCase().includes(searchTerm)
    );
  }

  return result;
});

// 是否有地址数据
const hasAddresses = computed(() => addresses.value.length > 0);

// --- 方法 ---
// 加载地址列表
const loadAddresses = async () => {
  try {
    isLoading.value = true;
    const addressList = await plcAddressStore.getAll();
    // 确保每个地址对象都有 rw 属性
    addresses.value = addressList.map(addr => ({
      ...addr,
      rw: addr.rw || 'R'  // 默认设置为 'R'
    }));
    logger.info(`已加载 ${addresses.value.length} 个 PLC 地址`);
  } catch (err) {  // 将 error 改为 err
    logger.error(`加载PLC地址列表失败: ${err.message}`);
    showNotification('加载地址列表失败', 'error');
  } finally {
    isLoading.value = false;
  }
};

// 工位名称映射
const getStationName = (station) => {
  const stationMap = {
    'station1': '工位1',
    'station2': '工位2'
  };
  return stationMap[station] || station;
};

// 类别名称映射
const getCategoryName = (category) => {
  const categoryMap = {
    'realtime': '实时工艺'
  };
  return categoryMap[category] || category;
};

// 导航到添加地址页面
const navigateToAddAddress = () => {
  router.push('/settings/plc-address-config/add');
};

// 编辑地址
const editAddress = (id) => {
  router.push(`/settings/plc-address-config/edit/${id}`);
};

// 删除相关的响应式数据
const goToDeleteConfirmPage = (address) => {
  logger.info(`跳转到删除PLC地址确认页面，地址: ${address.address}`);
  router.push(`/settings/plc-address-config/delete/${address.id}`);
};

// 清除搜索
const clearSearch = () => {
  filters.search = '';
};

// 重置筛选条件
const resetFilters = () => {
  filters.station = 'all';
  filters.category = 'all';
  filters.search = '';
};

// 显示通知
const showNotification = (message, type = 'success') => {
  notification.message = message;
  notification.type = type;
  notification.show = true;

  // 清除之前的定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId);
  }

  // 3秒后自动关闭
  notification.timeoutId = setTimeout(() => {
    notification.show = false;
  }, 3000);
};

// --- 生命周期钩子 ---
onMounted(async () => {

  await loadAddresses();
});

onBeforeUnmount(() => {
  // 清除通知定时器
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId);
  }
});

// ESC键返回功能
onMounted(() => {
  const handleEscape = (event) => {
    if (event.key === 'Escape') {
      router.back();
    }
  }
  document.addEventListener('keydown', handleEscape);

  // 在组件卸载时移除事件监听
  onBeforeUnmount(() => {
    document.removeEventListener('keydown', handleEscape);
  });
});

// 清理通知定时器
onBeforeUnmount(() => {
  if (notification.timeoutId) {
    clearTimeout(notification.timeoutId);
  }
});
</script>

<style scoped>
/* 整体容器 */
.plc-address-config {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: var(--bg-primary);
}

/* 主内容区域 */
main {
  flex: 1;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  overflow-y: auto;
}

/* 页面标题 */
.page-header {
  margin-bottom: 0.5rem;
}

.page-title {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.25rem;
}

.page-description {
  font-size: 0.875rem;
  color: var(--text-tertiary);
}

/* 操作栏 */
.actions-bar {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: 1rem;
  padding: 1rem 0;
}

/* 筛选器区域 */
.filters {
  display: flex;
  gap: 1rem;
  align-items: flex-end;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.filter-label {
  font-size: 0.75rem;
  color: var(--text-secondary);
  font-weight: 500;
}

.filter-select {
  width: 160px;
  height: 36px;
  padding: 0 0.75rem;
  border: 1px solid var(--border-color);
  border-radius: 0.375rem;
  background-color: white;
  font-size: 0.875rem;
  color: var(--text-primary);
  outline: none;
  transition: all 0.2s ease;
}

.filter-select:focus {
  border-color: var(--accent-blue);
  box-shadow: 0 0 0 2px var(--accent-blue-light);
}

/* 按钮区域 */
.actions {
  display: flex;
  gap: 1rem;
}

/* 表格容器 */
.table-container {
  flex-grow: 1;
  overflow: auto;
  background-color: var(--bg-secondary);
  border-radius: 0.5rem;
  border: 1px solid var(--border-color);
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  /* 自定义滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: var(--text-tertiary) var(--bg-primary);
}

/* Webkit浏览器的滚动条样式 */
.table-container::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

.table-container::-webkit-scrollbar-track {
  background: var(--bg-primary);
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb {
  background: var(--text-tertiary);
  border-radius: 4px;
}

.table-container::-webkit-scrollbar-thumb:hover {
  background: #555;
}

/* --- 表格样式 --- */
.address-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 0.875rem;
}

.address-table th,
.address-table td {
  padding: 0.75rem 1rem;
  text-align: left;
  border-bottom: 1px solid var(--border-color);
}

.address-table th {
  background-color: var(--bg-secondary);
  font-weight: 600;
  color: var(--text-secondary);
  font-size: 0.8rem;
  white-space: nowrap;
}

.address-table tr:last-child td {
  border-bottom: none;
}

.address-row:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.address-cell {
  font-family: 'Courier New', monospace;
  font-weight: 500;
}

.property-name-cell {
  font-family: 'Courier New', monospace;
  font-weight: 500;
  color: var(--accent-blue);
}

.description-cell {
  max-width: 250px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.actions-column {
  width: 80px;
  text-align: center;
}

.actions-cell {
  display: flex;
  gap: 0.5rem;
  justify-content: flex-end;
}

.table-action-btn {
  background: transparent;
  border: none;
  width: 2rem;
  height: 2rem;
  border-radius: 0.375rem;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: background-color 0.2s ease, color 0.2s ease;
}

.edit-btn {
  color: var(--text-secondary);
}

.edit-btn:hover {
  background-color: var(--accent-blue-light);
  color: var(--accent-blue);
}

.delete-btn {
  color: var(--text-secondary);
}

.delete-btn:hover {
  background-color: var(--status-red-light);
  color: var(--status-red);
}

/* --- 空状态样式 --- */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 1rem;
  text-align: center;
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
}

.empty-icon {
  font-size: 2.5rem;
  color: var(--text-tertiary);
  margin-bottom: 1rem;
  opacity: 0.3;
}

.empty-title {
  font-size: 1.125rem;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 0.5rem;
}

.empty-description {
  font-size: 0.875rem;
  color: var(--text-tertiary);
  margin-bottom: 1.5rem;
  max-width: 450px;
}

/* --- 加载状态样式 --- */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 3rem 1rem;
  text-align: center;
  background-color: white;
  border: 1px solid var(--border-color);
  border-radius: 0.5rem;
  gap: 1rem;
  font-size: 0.875rem;
  color: var(--text-tertiary);
}

.loading-state i {
  font-size: 1.5rem;
  color: var(--accent-blue);
}

/* --- 徽章样式 --- */
.station-badge, .category-badge, .rw-badge {
  display: inline-block;
  padding: 0.25rem 0.5rem;
  border-radius: 0.25rem;
  font-size: 0.75rem;
  font-weight: 500;
  white-space: nowrap;
}

.station-common {
  background-color: #e5e7eb;
  color: #4b5563;
}

.station-station1 {
  background-color: #dbeafe;
  color: #1e40af;
}

.station-station2 {
  background-color: #e0e7ff;
  color: #4338ca;
}

.category-process {
  background-color: #dcfce7;
  color: #166534;
}

.category-realtime {
  background-color: #dbeafe;
  color: #1e40af;
}

.category-control {
  background-color: #fef3c7;
  color: #92400e;
}

.category-status {
  background-color: #f3e8ff;
  color: #6b21a8;
}

.category-alarm {
  background-color: #fee2e2;
  color: #991b1b;
}

.rw-r {
  background-color: #e0f2fe;
  color: #0369a1;
}

.rw-w {
  background-color: #ffedd5;
  color: #9a3412;
}

.rw-rw {
  background-color: #f0fdf4;
  color: #166534;
}

/* --- 对话框样式 --- */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.dialog-container {
  background-color: white;
  border-radius: 0.5rem;
  box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);
  width: 90%;
  max-width: 450px;
  overflow: hidden;
}

.dialog-header {
  padding: 1rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid var(--border-color);
}

.dialog-title {
  font-size: 1rem;
  font-weight: 600;
  color: var(--text-primary);
}

.dialog-close {
  background: transparent;
  border: none;
  color: var(--text-tertiary);
  width: 2rem;
  height: 2rem;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.dialog-close:hover {
  background-color: rgba(0, 0, 0, 0.05);
  color: var(--text-primary);
}

.dialog-content {
  padding: 1.5rem 1rem;
}

.delete-info {
  margin: 1rem 0;
  padding: 0.75rem;
  background-color: var(--bg-secondary);
  border-radius: 0.375rem;
  border-left: 3px solid var(--accent-blue);
  font-size: 0.875rem;
}

.delete-warning {
  display: flex;
  align-items: flex-start;
  gap: 0.5rem;
  color: var(--status-red);
  font-size: 0.8rem;
  margin-top: 1rem;
}

.delete-warning i {
  margin-top: 0.125rem;
}

.dialog-footer {
  padding: 1rem;
  display: flex;
  justify-content: flex-end;
  gap: 0.75rem;
  border-top: 1px solid var(--border-color);
}

/* --- 按钮样式 --- */
.hmi-button {
  padding: 0.6rem 1rem;
  border-radius: 0.375rem;
  font-size: 0.875rem;
  font-weight: 600;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  gap: 0.4rem;
  border: 1px solid transparent;
  transition: all 0.2s ease;
  cursor: pointer;
}

.hmi-button i {
  font-size: 0.9em;
}

.hmi-button-primary {
  background-color: var(--accent-blue);
  color: white;
}

.hmi-button-primary:hover {
  background-color: #2563eb;
}

.hmi-button-secondary {
  background-color: white;
  color: var(--text-primary);
  border-color: var(--border-color);
}

.hmi-button-secondary:hover {
  background-color: #f9fafb;
  border-color: #d1d5db;
}

.hmi-button-danger {
  background-color: var(--status-red);
  color: white;
}

.hmi-button-danger:hover {
  background-color: #dc2626;
}

.hmi-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

/* --- 通知样式 --- */
.notification {
  position: fixed;
  bottom: 1rem;
  left: 50%;
  transform: translateX(-50%);
  padding: 0.75rem 1rem;
  border-radius: 0.375rem;
  color: white;
  font-weight: 500;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  z-index: 100;
  opacity: 0;
  visibility: hidden;
  animation: fadeInOut 3s ease-in-out forwards;
}

.notification-success {
  background-color: var(--status-green);
}

.notification-error {
  background-color: var(--status-red);
}

@keyframes fadeInOut {
  0% {
    opacity: 0;
    visibility: visible;
  }
  10% {
    opacity: 1;
  }
  90% {
    opacity: 1;
  }
  100% {
    opacity: 0;
    visibility: hidden;
  }
}

/* 响应式调整 */
@media (max-width: 768px) {
  .actions-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .filters {
    order: 2;
  }

  .actions {
    order: 1;
    margin-bottom: 0.5rem;
  }

  .filter-select {
    min-width: unset;
  }

  .search-group {
    min-width: unset;
    flex-grow: 1;
  }
}
</style>
